'use strict';
const express = require('express');
const router = express.Router();
const qs = require('querystring');
const crypto = require('crypto');
const xml = require('node-xml');
const request = require('request');

const wxapi = require('../wxapi');

// // 微信签名认证
// function sign(req, res) {
//     let signature = req.query.signature;
//     let timestamp = req.query.timestamp;
//     let nonce = req.query.nonce;
//     let echostr = req.query.echostr;
//     let token = config.token;

//     let list = [token, timestamp, nonce];
//     list.sort();
//     let original = list.join('');
//     let sha1 = crypto.createHash('sha1');
//     sha1.update(original);
//     let hashcode = sha1.digest('hex');
//     console.log('sign compare:%s <==> %s', hashcode, signature);
//     if (req.method == 'GET') {
//         if (hashcode == signature) {
//             res.send(echostr);
//         } else {
//             res.send('');
//         }
//     } else if (req.method == 'POST') {
//         if (hashcode == signature) {
//             return true;
//         } else {
//             return false;
//         }
//     }
//     return true;
// }

/* 微信公众号url认证 */
router.get('/', function (req, res, next) {
    wxapi.sign(req, res);
});

// 其他调用都使用POST
router.post('/', function (req, res, next) {
    if (wxapi.sign(req, res) == false) {
        return;
    }
    let post_data = '';
    req.on('data', function (data) { post_data += data; });
    req.on('end', function () {
        let xmlstr = post_data.toString('utf-8', 0, post_data.length);
        // 解析xml消息
        let ToUserName = '';
        let FromUserName = '';
        let CreateTime = '';
        let MsgType = '';
        let Content = '';
        let tempName = '';
        var parse = new xml.SaxParser(function (cb) {
            cb.onStartElementNS(function (elem, attra, prefix, uri, namespace) {
                tempName = elem;
            });
            cb.onCharacters(function (chars) {
                chars = chars.replace(/(^\s*)|(\s*$)/g, '');
                if (tempName == 'CreateTime') {
                    CreateTime = chars;
                }
            });
            cb.onCdata(function (cdata) {
                if (tempName == 'ToUserName') {
                    ToUserName = cdata;
                } else if (tempName == 'FromUserName') {
                    FromUserName = cdata;
                } else if (tempName == 'MsgType') {
                    MsgType = cdata;
                } else if (tempName == 'Content') {
                    Content = cdata;
                }
                //console.log(tempName + ':' + cdata);
            });
            cb.onEndElementNS(function (elem, prefix, uri) {
                tempName = '';
            });
            cb.onEndDocument(function () {
                let objMsg = {
                    ToUserName: ToUserName,
                    FromUserName: FromUserName,
                    CreateTime: CreateTime,
                    MsgType: MsgType,
                    Content: Content,
                };
                if (MsgType === 'event') {
                    // 用户点击菜单
                } else if (MsgType === 'text') {
                    // 自动回复消息
                    EventFunction.replyMsg(objMsg, res);
                }
            });
        });
        parse.parseString(xmlstr);
    });
});

var EventFunction = {
    // 自动回复
    replyMsg: function (objMsg, res) {
        let msg = '谢谢关注,你说的是:' + objMsg.Content;
        let createTime = parseInt(new Date().getTime() / 1000);
        // 组织返回数据包
        var sendMessage = '<xml><ToUserName><![CDATA[' +
            objMsg.FromUserName + ']]></ToUserName><FromUserName>' +
            '<![CDATA[' + objMsg.ToUserName + ']]></FromUserName>' +
            '<CreateTime>' + createTime + '</CreateTime><MsgType>' +
            '<![CDATA[text]]></MsgType><Content><![CDATA[' + msg +
            ']]></Content></xml>';
        res.send(sendMessage);
    }
};

module.exports = router;
